﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace Easily
{
    public partial class frmConfig : Form
    {
        private GeneralIcon MyIcon = null;  //保存调用本构造函数的图形化控件信息
        private string hardUSB = "";
        /// <summary>
        /// 构造函数，完成创建窗体及保存调用本构造函数的图形化控件信息
        /// </summary>
        /// <param name="icon"></param>
        public frmConfig(GeneralIcon icon)
        {
            InitializeComponent();
            this.MyIcon = icon;  //保存图形化控件信息
            if (icon.info.type != "事件控件")  //事件控件不需要功能设置
                createControl();     //自动创建本窗体的控件
            //[2021/1/30] 应该用IconName去取USB口
            if (Globaldefine.loadConfig.dicHard_USB != null && Globaldefine.loadConfig.dicHard_USB.ContainsKey(MyIcon.IconName))
                hardUSB = Globaldefine.loadConfig.dicHard_USB[MyIcon.IconName];

            //添加可供选择的硬件接口
            if (this.MyIcon.info.name == "可调亮度小灯")
            {
                //this.label1.Visible = false;
                hardUSB = "J4";
            }
            if (this.MyIcon.info.name == "内置三色灯")
            {
                //this.label1.Visible = false;
                hardUSB = "INNER_LIGHT";
            }
            if (this.MyIcon.info.name=="小车")
            {
                //this.label1.Visible = false;
                hardUSB = "J9J10";
            }
            if (this.MyIcon.info.name == "冰箱-NB")
            {
                //this.label1.Visible = false;
                hardUSB = "J1";
            }
            //[2021/4/19] 智能拐杖-NB模块 需要单独处理参数 因为它的参数有多个
            if (MyIcon.ModuleName == "智能拐杖-NB" &&
                Globaldefine.loadConfig.dicHard_USB.ContainsKey("超声波传感器1"))
            {
                //usbNum_btn, usbNum_acc, usbNum_beef, usbNum_motor, usbNum_uw1, usbNum_uw2
                hardUSB = Globaldefine.loadConfig.dicHard_USB["触发式开关"] + ","
                    + Globaldefine.loadConfig.dicHard_USB["加速度传感器"] + ","
                    + Globaldefine.loadConfig.dicHard_USB["蜂鸣器"] + ","
                    + Globaldefine.loadConfig.dicHard_USB["电机"] + ","
                    + Globaldefine.loadConfig.dicHard_USB["超声波传感器"] + ","
                    + Globaldefine.loadConfig.dicHard_USB["超声波传感器1"];
            }

            //初始化控件初值
            if (this.MyIcon.code.Save != "")  //加载已保存的控件信息
            {
                string[] tmp = this.MyIcon.code.Save.Split(';');
                //comboBox1.SelectedItem = tmp[0];
                for (int i = 0; i < flowLayoutPanel1.Controls.Count; i++)
                {
                    switch (MyIcon.info.funs[i].param_type)
                    {
                        case "void":
                            break;
                        case "radiobtn":
                            //2021/1/22 把生成下拉框替换成生成单选按钮
                            TableLayoutPanel panel = (TableLayoutPanel)flowLayoutPanel1.Controls[i].Controls[1];
                            foreach (RadioButton radioButton in panel.Controls)
                            {
                                //若存储信息等于radioButton显示文本 则表示它之前被选中
                                if (radioButton.Text == tmp[i + 1])
                                {
                                    radioButton.Checked = true;
                                    break;
                                }
                            }
                            //((ComboBox)(flowLayoutPanel1.Controls[i].Controls[1])).SelectedItem = tmp[i + 1]; 
                            break;
                        case "textbox": ((TextBox)(flowLayoutPanel1.Controls[i].Controls[1])).Text = tmp[i + 1]; break;
                    }
                }
            }
            createCode();//根据配置生成代码
            //this.label1.Text = this.MyIcon.ModuleName;  //显示模块名
            //[2021/1/30]
            this.Text = this.MyIcon.IconName;  //显示模块名
        }
        private void FrmConfig_Load(object sender, EventArgs e)
        {
            createCode();
        }

        /// <summary>
        /// 点击“确定”按钮
        /// 主要功能：根据配置生成新代码，并设置对话返回为OK
        /// </summary>
        private void Btn_confirm_Click(object sender, EventArgs e)
        {
            createCode();//根据配置生成代码
            this.DialogResult = DialogResult.OK;
        }

        /// <summary>
        /// 单击“取消”按钮
        /// 主要功能：设置返回结果为取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Cancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        #region 内部函数
        /// <summary>
        /// 根据MyIcon.info.funs（即配置文件内容）自动生成控件
        /// 自动生成的控件由一个label（存储“description”）+一个label/textbox/radiobtn（由“param_type”指定）组成
        /// 将上述两个控件放在一个流控件flowLayoutPanel中做为一个整体，然后再将所有的流控件放入一个更大的流控件中
        /// </summary>
        /// <returns></returns>
        private bool createControl()
        {
            try
            {
                if (MyIcon.info.funs == null) return true;  //无需创建控件
                foreach (LoadConfig.FUN fun in MyIcon.info.funs)
                {
                    if (fun == null || fun.name == "") continue; //未定义此函数
                    Label label = new Label();
                    FlowLayoutPanel flowLayoutPanel = new FlowLayoutPanel
                    {
                        FlowDirection=FlowDirection.TopDown
                    };
                    object obj = null;
                    //设置label
                    label.Font = new System.Drawing.Font("宋体", 12F);
                    label.Text = fun.description;
                    label.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
                    label.AutoSize = true;
                    //设置参数框
                    switch (fun.param_type)
                    {
                        case "void":
                            obj = new Label(); break;
                        case "radiobtn":
                            //2021/1/22 把生成下拉框替换成生成单选按钮
                            //ComboBox comboBox = new ComboBox();
                            //foreach (LoadConfig.PARAM_VALUE v in fun.param_values)
                            //{
                            //    comboBox.Items.Add(v.description);
                            //}
                            //obj = comboBox;
                            TableLayoutPanel panel = new TableLayoutPanel
                            {
                                AutoSize=true
                            };//存放所有单选按钮
                            //根据Config.json的读取信息 生成单选按钮 并添加到panel中
                            foreach (LoadConfig.PARAM_VALUE v in fun.param_values)
                            {
                                RadioButton radioButton = new RadioButton
                                {
                                    Text = v.description
                                };
                                panel.Controls.Add(radioButton);
                            }
                            obj = panel;
                            break;
                        case "textbox":
                            TextBox textBox = new TextBox();
                            obj = textBox;
                            break;
                    }
                    flowLayoutPanel.Width = flowLayoutPanel1.Width;
                    flowLayoutPanel.Height = flowLayoutPanel1.Height;
                    //添加至流容器中
                    flowLayoutPanel.Controls.Add(label);
                    flowLayoutPanel.Controls.Add((Control)obj);
                    this.flowLayoutPanel1.Controls.Add(flowLayoutPanel);
                }
                return true;
            }
            catch
            {
                MessageBox.Show("生成配置窗体失败，请检查配置文件！");
                return false;
            }
        }
        /// <summary>
        /// 生成保存于MyIcon.code中的内容
        /// </summary>
        private void createCode()
        {
            MyIcon.code.Clear();//清空以前代码
            //添加头文件、初始化代码等
            this.MyIcon.code.HeadFile = "#include \"" + MyIcon.info.head_file + "\""; //添加构件的头文件
            //[2021/1/30]
            if(MyIcon.info.init_fun != "")
                this.MyIcon.code.Initialization = this.MyIcon.info.init_fun + "(" + hardUSB + ");//初始化" + MyIcon.IconName;
            //MyIcon.code.Save = hardUSB;
            //[2021/1/31]
            if (MyIcon.info.type == "事件控件")
            {
                //添加中断代码
                //[2021/1/31]中断开始函数不应该放在这里 每一个中断使用的都是PORTC_PORTD_IRQHandler
                //所以应该去掉原有的funs[0]即中断服务例程函数，每个GPIO事件控件里面只要一个功能函数即可
                //MyIcon.code.InterruptServiceStart += "void PORTC_PORTD_IRQHandler(void)\r\n{\r\n"
                //      + "\tDISABLE_INTERRUPTS;                       //关总中断\n";
                //红外循迹的实现和其他事件控件不一样
                //if (MyIcon.ModuleName == "红外循迹")
                //{
                //    MyIcon.code.GlobalVariable = " uint16_t  ray_Trace_flag;        //记录红外循迹左右检测情况的标记\r\n";
                //    MyIcon.code.InitVariable = "ray_Trace_flag = 0;\r\n";
                //    MyIcon.code.InterruptServiceStart += "\t"+ "ray_Trace_flag = " + MyIcon.info.funs[0].name + "(" + this.hardUSB + ");\r\n\t";
                //}
                //else
                //{
                //[2021/3/31]加入对应注释
                MyIcon.code.InterruptServiceStart += "\tif(" + MyIcon.info.funs[0].name + "(" + this.hardUSB + "))"
                    +"//"+ MyIcon.info.funs[0].description + "\r\n\t{\r\n\t";
                MyIcon.code.InterruptServiceEnd += "\t}\n";
                MyIcon.code.Comment += MyIcon.info.funs[0].description;
                //}
            }
            else
            {
                if(MyIcon.info.funs!=null)
                {
                    for (int i = 0; i < MyIcon.info.funs.Count; i++)
                    {
                        FlowLayoutPanel f = ((FlowLayoutPanel)(flowLayoutPanel1.Controls[i]));
                        string description = "", name = ""; //函数参数的描述信息和名称
                        switch (MyIcon.info.funs[i].param_type)
                        {
                            case "void":
                                break;
                            case "radiobtn":
                                //2021/1/22 把生成下拉框替换成生成单选按钮
                                //ComboBox c = (ComboBox)(f.Controls[1]);
                                //if (c.SelectedItem == null)
                                //    break;
                                //description = c.SelectedItem.ToString();
                                //name = MyIcon.info.funs[i].param_values[c.SelectedIndex].name;
                                TableLayoutPanel panel = (TableLayoutPanel)(f.Controls[1]);
                                for (int j = 0; j < panel.Controls.Count; j++)
                                {
                                    RadioButton radioButton = (RadioButton)panel.Controls[j];
                                    if (radioButton.Checked)
                                    {
                                        description = radioButton.Text.ToString();
                                        name = MyIcon.info.funs[i].param_values[j].name;
                                        break;
                                    }
                                }

                                break;
                            case "textbox":
                                TextBox t = (TextBox)(f.Controls[1]);
                                description = name = t.Text.ToString();
                                break;
                        }
                        string insertVar = "";
                        switch (MyIcon.info.funs[i].return_type)
                        {
                            case "void": break;
                            case "char*":
                            case "uint16_t":
                                //【2021/3/11】这里的局部变量取名 需要根据MyIcon.IconName来区分开
                                //如果是外设
                                if (Globaldefine.loadConfig.control_Cnt.Keys.Contains(MyIcon.ModuleName))
                                {
                                    //有多个外设 那么该外设的IconName中一定包含数字 否则就是加入的第一个外设
                                    //【0 - 9】意思就是只要是范围0 - 9里的东西都要，或者说只要不是数字都不要
                                    //+的意思的 [0-9]的范围里匹配一次以上。$是匹配结束符
                                    Match match = Regex.Match(MyIcon.IconName, "[0-9]+$");
                                    if (match.Success)
                                    {
                                        insertVar = "b" + hardUSB + "_" + MyIcon.info.funs[i].name + match.Value;
                                    }
                                    else
                                    {
                                        insertVar = "b" + hardUSB + "_" + MyIcon.info.funs[i].name;
                                    }
                                    //insertVar = "b" + hardUSB + "_" + MyIcon.ModuleName;
                                    MyIcon.code.LocalVariable += MyIcon.info.funs[i].return_type + " " + insertVar
                                        + ";//存储" + hardUSB + "口连接的" + MyIcon.ModuleName + "获取的数据\r\n";
                                    if (Globaldefine.FrmParent.ActivedrmGraphicFlow != null)
                                    {
                                        //为该外设控件添加对应局部变量
                                        Globaldefine.FrmParent.ActivedrmGraphicFlow.m_Sensor_VariableLocal[MyIcon.IconName] = insertVar;
                                        //else
                                        //{

                                        //    for (int j = 0; j < Globaldefine.FrmParent.ActivedrmGraphicFlow.m_VariableLocal.Count; j++)
                                        //    {
                                        //        if (Globaldefine.FrmParent.ActivedrmGraphicFlow.m_VariableLocal[j].ToString().Contains(insertVar.Substring(3)))
                                        //            Globaldefine.FrmParent.ActivedrmGraphicFlow.m_VariableLocal.RemoveAt(j);
                                        //    }
                                        //    Globaldefine.FrmParent.ActivedrmGraphicFlow.m_VariableLocal.Add(insertVar);
                                        //}
                                    }

                                }


                                insertVar += " = ";
                                break;
                            case "textbox":
                                TextBox t = (TextBox)(f.Controls[1]);
                                description = name = t.Text.ToString();
                                break;
                        }
                        string s = "," + name; //在无第二个参数时，删除多余的逗号
                        if (name == "") s = "";
                        //生成注释和插入代码
                        if (!Globaldefine.loadConfig.control_Cnt.Keys.Contains(MyIcon.ModuleName))
                        {
                            //未选择外设的状态
                            if (description == "")
                            {
                                MyIcon.code.Comment += MyIcon.info.funs[i].description + "：" + "未选择状态" + "\r\n";
                                MyIcon.code.InsertCode += "\t" + insertVar + MyIcon.info.funs[i].name + "(" + hardUSB + s
                                + ");//" + MyIcon.info.funs[i].description + "：" + "未选择状态" + "\r\n";
                            }
                            else
                            {
                                MyIcon.code.Comment += MyIcon.info.funs[i].description + "：" + description + "\r\n";
                                MyIcon.code.InsertCode += "\t" + insertVar + MyIcon.info.funs[i].name + "(" + hardUSB + s
                                    + ");//" + MyIcon.info.funs[i].description + "：" + description + "\r\n";
                            }
                        }
                        else
                        {
                            
                            MyIcon.code.Comment += MyIcon.info.funs[i].description + "\r\n";
                            MyIcon.code.InsertCode += "\t"+insertVar + MyIcon.info.funs[i].name + "(" + hardUSB + s
                            + ");//" + MyIcon.info.funs[i].description + "\r\n";
                        }
                        MyIcon.code.Save += ";" + description;
                    }
                    //if (MyIcon.code.GlobalVariable != "")
                    //    MyIcon.code.GlobalVariable = MyIcon.code.GlobalVariable.Substring(0, MyIcon.code.GlobalVariable.Length - 2);
                    if (MyIcon.code.InsertCode != "")  //若有代码插入，则删除最后的换行
                    {
                        MyIcon.code.Comment = MyIcon.code.Comment.Substring(0, MyIcon.code.Comment.Length - 2);
                        MyIcon.code.InsertCode = MyIcon.code.InsertCode.Substring(0, MyIcon.code.InsertCode.Length - 2);
                    }
                }
                    
            }
        }

        #endregion

        private void flowLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}
